<?php

declare(strict_types=1);

namespace app\common\exception;

use app\common\enum\RespCode;
use think\Exception;
use think\facade\Db;
use think\Response;

/**
 * DB事务处理
 */
class TransException
{
    /**
     * @param string $class 类名
     * @param string $method 执行方法
     * @param ...$argc 参数
     */
    public static function exec($class, $method, ...$argc): Response
    {
        Db::startTrans();
        try {
            $result = call_user_func_array([make($class), $method], $argc);
            Db::commit();
            return self::respData($result, '请求成功', RespCode::SUCCESS);
        } catch (TipsException $e) {
            Db::rollback();
            return self::respData('', $e->getMessage(), RespCode::ERROR);
        } catch (Exception $e) {
            Db::rollback();
            return self::respData('', env('APP_DEBUG') ? $e->getMessage() : RespCode::DEF_TIPS, RespCode::ERROR);
        }
    }
    /**
     * response
     */
    private static function respData($data, $message, $code): Response
    {
        return resp_header(null, ['code' => $code, 'message' => $message, 'data' => $data]);
    }
}
